package com.studyyoun.android.androidcommonbaselibrary.okhttp.qequest;

import java.io.File;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.*;

/**
 * Created by androidlongs on 17/6/28.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 * <p>
 * <p>
 * Okhttp 请求Request封装
 */

public class OkhttpCommonRequest {


    /**
     * 创建 post Request对象
     *
     * @return post Request对象
     */
    public static Request createPosRequest (String url, ConcurrentHashMap<String, String> hashMap) {

        FormBody.Builder formBodyBuild = new FormBody.Builder();

        //封装请求参数
        if (hashMap != null && !hashMap.isEmpty()) {
            for (Entry<String, String> entry : hashMap.entrySet()) {
                formBodyBuild.add(entry.getKey(), entry.getValue());
            }
        }

        //构建请求对象
        FormBody formBody = formBodyBuild.build();

        return new Request.Builder().url(url).post(formBody).build();
    }

    /**
     * 创建 Get Request对象
     *
     * @return Get Request对象
     */
    public static Request createGetRequest (String url, ConcurrentHashMap<String, String> hashMap) {


        StringBuilder stringBuilder = new StringBuilder(url).append("?");
        //封装请求参数
        if (hashMap != null && !hashMap.isEmpty()) {
            for (Entry<String, String> entry : hashMap.entrySet()) {
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }

        return new Request.Builder().url(stringBuilder.substring(0, stringBuilder.length() - 1)).get().build();
    }
    /**
     * 创建 post File Request对象
     *
     * @return post File Request对象
     */
    public static Request createPosFileRequest (String url, ConcurrentHashMap<String, Object> hashMap) {


        MultipartBody.Builder builder = new MultipartBody.Builder();
        //设置类型
        builder.setType(MultipartBody.FORM);
        //追加参数
        for (String key : hashMap.keySet()) {
            Object object = hashMap.get(key);
            if (!(object instanceof File)) {
                builder.addFormDataPart(key, object.toString());
            } else {
                File file = (File) object;
                builder.addFormDataPart(key, file.getName(), RequestBody.create(null, file));
            }
        }

        //创建RequestBody
        RequestBody body = builder.build();

        return new Request.Builder().url(url).post(body).build();
    }
}
